<template>
  <div>
    <el-card class="box-card">
      <el-form :inline="true" :model="formMu" class="demo-form-inline">
        <el-form-item label="菜单名称">
          <el-input v-model="formMu.name" placeholder="菜单名称"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit()">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card">
      <!-- 下拉框递归菜单树 -->
      <el-table
        ref="singleTable"
        :data="tableData"
        highlight-current-row
        row-key="id"
        @current-change="handleCurrentChange"
        :tree-props="{ children: 'childMenus', hasChildren: 'hasChildren' }"
        style="width: 100%"
      >
        <el-table-column label width="35" type="">
          <template slot-scope="scope">
            <el-radio :label="scope.row.id" v-model="id">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column property="name" label="菜品分类" width="140">
        </el-table-column>
        <el-table-column prop="img" label="轮播图片">
          <template slot-scope="scope">
            <el-popover placement="right" trigger="hover">
              <img :src="scope.row.img" class="imgs" />
              <img
                slot="reference"
                :src="scope.row.img"
                style="max-height: 50px; max-width: 150px"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          type=""
          property="sort"
          label="排序"
          width="90"
          align="center"
        >
        </el-table-column>
        <el-table-column
          type=""
          property="createTime"
          label="创建时间"
          align="center"
        >
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="toUpdate(scope.row.id)"
              v-if="scope.row.pid != 0"
              >修改</el-button
            >
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              @click="toInsert"
              v-if="scope.row.pid != 0"
              >新增</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="del(scope.row.id)"
              v-if="scope.row.pid != 0"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :title="flag"
    >
      <!-- 添加表单 -->
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item>
          <el-input v-model="form.id" v-if="false"></el-input>
        </el-form-item>
        <el-form-item label="菜单图片" placeholder="img">
          <img :src="form.img" class="imgs" />
          <!-- 文件上传按钮 -->
          <el-button
            type="primary"
            icon="el-icon-upload"
            @click="imagecropperShow = true"
          >
          </el-button>
          <!--
                v-show：是否显示上传组件
                :key：类似于id，如果一个页面多个图片上传控件，可以做区分
                :url：后台上传的url地址
                @close：关闭上传组件
                @crop-upload-success：上传成功后的回调 -->
          <image-cropper
            v-show="imagecropperShow"
            :width="240"
            :height="120"
            :key="imagecropperKey"
            :url="'/oss/uploadImgFile'"
            field="file"
            @close="closeImage"
            @crop-upload-success="cropSuccess"
          />
        </el-form-item>
        <el-form-item label="菜品名称">
          <el-input v-model="form.name" placeholder="输入菜品名称"></el-input>
        </el-form-item>
        <!-- 只能回显pid，，因为后台传到前台的id被转换为string字符串类型 -->
        <el-form-item label="菜品层级">
          <el-select
            v-model="form.pid"
            placeholder="请选择父级菜单"
            style="width: 80%"
            clearable
          >
            <el-option
              :value="id"
              :label="name"
              style="height: 150px; overflow: auto; background-color: #fff"
            >
              <el-tree
                :data="tableData"
                :props="defaultProps"
                @node-click="handleNodeClick"
              ></el-tree>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品顺序">
          <el-input-number
            v-model="form.sort"
            @change="handleChange"
            :min="1"
            :max="100"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="结束时间">
          <div class="block">
            <el-date-picker
              v-model="form.updateTime"
              type="datetime"
              format="yyyy-MM-dd HH:MM:SS"
              value-format="yyyy-MM-dd HH:MM:SS"
              placeholder="选择结束时间"
            >
            </el-date-picker>
          </div>
        </el-form-item>

        <el-form-item label="创建人">
          <el-input v-model="form.createUser" placeholder="创建人"></el-input>
        </el-form-item>
        <el-form-item label="更新人">
          <el-input v-model="form.updateUser" placeholder="更新人"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="editUser">{{ flag }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  categoryTree,
  insert,
  update,
  selectById,
  deleteById,
  selectAllByName,
} from "../../api/cate";
import ImageCropper from "../../components/ImageCropper";
import PanThumb from "../../components/PanThumb";
export default {
  components: { ImageCropper, PanThumb },
  data() {
    return {
      //控制显示advAdd层的显示、

      defaultProps: {
        children: "childMenus",
        label: "name",
      },
      dialogVisible: false,
      flag: "添加",
      imagecropperShow: false, // 是否显示上传组件
      imagecropperKey: 0, // 上传组件id
      field101Action: "https://jsonplaceholder.typicode.com/posts/",
      field101fileList: [],
      id: "",
      name: "",
      status: "",
      img: "",
      tableData: [],
      childMenus: [],
      multipleSelection: [],

      formMu: {},
      form: {
        id: "",
        name: "",
        pid: "",
        level: "",
        sort: "",
        updateTime: "",
        createTime: "",
        updateUser: 1,
        createUser: 1,
        img: "",
      },
    };
  },
  methods: {
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row);
      this.id = row.id;
    },

    handleCurrentChange(id) {
      this.id = this.tableData.id;
    },

    // 树形下拉点击调用
    handleNodeClick(data) {
      this.id = data.id;
      // el-select 值和 el-option 值对应上才能显示
      this.$set(this.form, "pid", data.id);
      this.name = data.name;
    },

    //获取菜单树
    async getMenuTree() {
      let result = await categoryTree();
      this.tableData = result.data.tree;
      console.log(result);
    },
    async sleectAll() {
      let result = await selectAllByName(this.formMu.name);
      this.tableData = result.data.categoryList;
      console.log(result);
    },
    //新增
    async insert() {
      var $this = this;
      let result = await insert(this.form);
      if (result.data.code === 200) {
        //弹出消息
        $this.$message({
          message: "新增成功",
          type: "success",
          duration: 2000,
        });

        //关闭窗体
        $this.dialogVisible = false;
        //查询数据
        $this.getMenuTree();
        //清空数据
        $this.form = {};
        //  $this.form.pid = "";
      } else {
        //弹出消息
        $this.$message({
          message: "父节点不能是最后的子节点",
          type: "success",
          duration: 2000,
        });
        //查询数据
        $this.getMenuTree();
      }
    },
    //修改
    async update() {
      var $this = this;
      let result = await update(this.form);
      if (result.data.code === 200) {
        //弹出消息
        $this.$message({
          message: "修改成功",
          type: "success",
          duration: 2000,
        });
        //关闭窗体
        $this.dialogVisible = false;
        //查询数据
        $this.getMenuTree();
        //清空数据
        $this.form = {};
      } else if (result.data.code === 1) {
        //弹出消息
        $this.$message({
          message: "父节点不能是自己",
          type: "success",
          duration: 2000,
        });
        //查询数据
        $this.getMenuTree();
      } else {
        //弹出消息
        $this.$message({
          message: "父节点不能是最后的子节点",
          type: "success",
          duration: 2000,
        });
        //查询数据
        $this.getMenuTree();
      }
    },
    //删除
    async deleteById(id) {
      var $this = this;
      let result = await deleteById(id);
      if (result.data.code === 200) {
        //弹出消息
        $this.$message({
          message: "删除成功",
          type: "success",
          duration: 2000,
        });
        //查询数据
        $this.getMenuTree();
      } else {
        //弹出消息
        $this.$message({
          message: "父节点下有子节点不能删除",
          type: "success",
          duration: 2000,
        });
        //查询数据
        $this.getMenuTree();
      }
    },
    //根据id回显
    async selectAllById(id) {
      let result = await selectById(id);
      this.form = result.data.category;
      let res = await selectById(this.form.pid);
      const formData = res.data.category;
      this.id = formData.id;
      this.name = formData.name;
    },
    onSubmit() {
      if (this.formMu.name == "") {
        this.getMenuTree();
      } else {
        this.sleectAll();
      }
    },
    load(tree, treeNode, childMenus) {
      setTimeout(() => {
        childMenus([{}]);
      }, 1000);
    },
    handleChange(sort) {
      console.log(sort);
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.form = {};
          this.dialogVisible = false;
          done();
        })
        .catch((_) => {});
    },
    del(id) {
      this.$confirm("确认删除？")
        .then((_) => {
          this.deleteById(id);
          done();
        })
        .catch((_) => {});
    },
    editUser() {
      if (this.flag === "添加") {
        this.insert();
      } else {
        this.update();
      }
    },
    toInsert() {
      (this.dialogVisible = true), (this.flag = "添加");
    },
    toUpdate(id) {
      (this.dialogVisible = true), (this.flag = "修改");
      //通过Id查询用户信息
      this.selectAllById(id);
    },
    field101BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      let isAccept = new RegExp("image/*").test(file.type);
      if (!isAccept) {
        this.$message.error("应该选择image/*类型的文件");
      }
      return isRightSize && isAccept;
    },
    // 上传成功后的回调函数
    cropSuccess(data) {
      var oldImage = this.form.img;
      this.imagecropperShow = false;
      this.form.img = data.url;
      console.log(this.form.img);
      // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1;
      //上传成功之后删除之前的头像
      this.deleteAvatar(oldImage);
    },

    // 关闭上传组件
    closeImage() {
      this.imagecropperShow = false;
      // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1;
    },
    //删除上传之前的图片
    async deleteAvatar(oldImage) {
      const { data } = await deleteImgFile(oldImage);
    },
  },
  //窗体加载事件
  created() {
    this.getMenuTree();
  },
};
</script>

<style lang="less" scoped>
.box-card {
  margin: 20px;
}
.el-table_1_column_3 is-center is-leaf el-table__cell {
  width: 150px;
}
</style>